package com.lyncs.ods.utils;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONValidator;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author alex
 * @date 2022/4/3 23:06
 * @description 阿里产品工具类
 */
@Slf4j
public class AliUtils {

    public static final String SMS_URL = "https://dysmsapi.aliyuncs.com/?Action=SendSms&PhoneNumbers=%s&SignName=%s&TemplateCode=%s&TemplateParam=%s&Version=%s";
    public static final String ENDPOINT = "dysmsapi.aliyuncs.com";


    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = ENDPOINT;
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args) throws Exception {
        com.aliyun.dysmsapi20170525.Client client = createClient("LTAI5tL4ZzNSzqBr4sD5yxge", "XM2dDWxcj38C55MwHMPhKqFl0kAKU5");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("阿里云短信测试")
                .setPhoneNumbers("15297746757")
                .setTemplateCode("SMS_154950909")
                .setTemplateParam("{\"code\":1234}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        log.info("response:{}", sendSmsResponse);
    }

    public static <T> String sendSms(String accessKeyId, String accessKeySecret, String phone, String sign, String code, String param, Consumer<T> successFunc, Consumer<T> failedFunc, T data) {
        Client client = null;
        try {
            client = createClient(accessKeyId, accessKeySecret);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setSignName(sign)
                    .setPhoneNumbers(phone)
                    .setTemplateCode(code)
                    .setTemplateParam(param);
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponseBody sendSmsResponseBody = client.sendSms(sendSmsRequest).getBody();
            String resp = JSONObject.toJSONString(sendSmsResponseBody);
            log.info("ali sms,templateCode:{},param:{} response:{}", code, JSONObject.toJSONString(param), resp);
            if (Objects.nonNull(sendSmsResponseBody) && sendSmsResponseBody.getCode().equals("OK")) {
                if (successFunc != null) {
                    successFunc.accept(data);
                }
            } else {
                if (failedFunc != null) {
                    failedFunc.accept(data);
                }
            }
            return resp;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> String sendSms(String phone, String sign, String code, String param, Consumer<T> successFunc, Consumer<T> failedFunc, T data) {
        String url = String.format(SMS_URL, phone, sign, code, param, LocalDate.now());
        String result = HttpUtil.get(url);
        if (StringUtils.isEmpty(result) || !JSONValidator.from(result).validate()) {
            log.error("send sms failed, phone:{}, code:{}", phone, code);
            return null;
        }
        JSONObject retJson = JSONObject.parseObject(result);
        if (Objects.nonNull(retJson) && "OK".equals(retJson.getString("Code"))) {
            successFunc.accept(data);
        } else {
            failedFunc.accept(data);
        }
        return retJson.getString("BizId");
    }

    public static <T> String senSmsCode(String phone, Consumer<T> successFunc, Consumer<T> failedFunc, T data) {
        final String templateCode = "SMS_238250828";
        //TODO:未申请
        final String sign = "";
        String code = RandomUtil.randomNumbers(4);
        JSONObject param = new JSONObject() {{
            put("code", code);
        }};
        return sendSms(phone, sign, templateCode, JSON.toJSONString(param), successFunc, failedFunc, data);
    }

    /*public static void main(String[] args) {
        String bizCode = senSmsCode("15297746757", System.out::println, System.out::println, "test");
        System.out.println(bizCode);
    }*/
}
